/**
 * @Title: LoadingActivity.java
 * @Package: com.jason.fingerprint.ui
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月29日15:24:29
 * @Version: V1.0
 */
package com.jason.fingerprint.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.beans.LoginReq;
import com.jason.fingerprint.beans.UserBean;
import com.jason.fingerprint.beans.VersionBean;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.configs.HttpConfig;
import com.jason.fingerprint.logic.DownloadSyncLogic;
import com.jason.fingerprint.logic.GetVersionSyncLogic;
import com.jason.fingerprint.logic.LoginSyncLogic;
import com.jason.fingerprint.service.InitService;
import com.jason.fingerprint.utils.ToastUtil;
import com.jason.fingerprint.widget.LoadingDialog;

import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.SystemTool;

import java.io.File;

/**
 * @ClassName: LoadingActivity
 * @Description: 程序启动页面，以及数据初始化
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月22日 下午9:29:16
 */
public class LoadingActivity extends BaseActivity {

    private static final String TAG = "LoadingActivity";
    private static final int LOADING_TIME = 1500;
    private AppContext mAppContext;
    private Context mContext;
    private KJDB mKjdb;
    private LoadingDialog mProgressDialog;
    private boolean mIsHasInit = false;

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_loading);
    }

    /*
     * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initData()
     */
    @Override
    protected void initData() {
        super.initData();
        initPermission();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initPermission() {
        //检查权限
        if (!selfPermissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE) ||
                !selfPermissionGranted(Manifest.permission.READ_EXTERNAL_STORAGE) ||
                !selfPermissionGranted(Manifest.permission.CALL_PHONE) ||
                !selfPermissionGranted(Manifest.permission.ACCESS_FINE_LOCATION) ||
                !selfPermissionGranted(Manifest.permission.ACCESS_COARSE_LOCATION) ||
                !selfPermissionGranted(Manifest.permission.RECORD_AUDIO)) {
            requestCameraPermission(new PermissionHandler() {
                @Override
                public void onGranted() {
                    Log.i(TAG, "onGranted");
                    if (mIsHasInit) {
                        return;
                    }
                    mIsHasInit = true;
                    //启动初始化服务
                    AppContext.getInstance().initDB();
                    AppContext.getInstance().initBuglyReport();
                    startService(new Intent(LoadingActivity.this, InitService.class));
                    init();
                }

                @Override
                public void onDenied() {
                    super.onDenied();
                    Log.i(TAG, "onDenied");
                    ToastUtil.showToast(LoadingActivity.this, "部分权限没有授权，无法进入程序");
                    LoadingActivity.this.finish();
                }
            });
        } else {
            if (mIsHasInit) {
                return;
            }
            mIsHasInit = true;
            AppContext.getInstance().initDB();
            AppContext.getInstance().initBuglyReport();
            startService(new Intent(LoadingActivity.this, InitService.class));
            init();
        }
    }

    @Override
    protected void initWidget() {
        super.initWidget();
    }

    private void init() {
        mAppContext = (AppContext) getApplication();
        mContext = getApplicationContext();
        mKjdb = mAppContext.getKjdb();
        try {
            mKjdb.deleteTable(UserBean.class);
            if (AppContext.getInstance().isSynchronizedRecord()) {
                mKjdb.deleteTable(FingerPrintBean.class);
            } else {
                //删除工作人员的指纹信息
                mKjdb.deleteByWhere(FingerPrintBean.class, "type = 2");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mProgressDialog = new LoadingDialog(this);
        if (SystemTool.checkNet(mContext)) {
            // 同步之前需要清空数据库中该表的数据
            if (AppContext.BUGLY_DEBUG) {
                Intent intent = new Intent(LoadingActivity.this, HomeActivity.class);
                intent.putExtra("is_to_loading_activity", true);
                startActivity(intent);
                finish();
            } else {
                checkVersion();
            }
        } else {
            new Handler().postDelayed(mRunnable, LOADING_TIME);
        }
    }

    private void checkVersion() {
        mProgressDialog.setIsOut(false);
        mProgressDialog.setMessage("检查更新中...");
        mProgressDialog.show();
        GetVersionSyncLogic logic = new GetVersionSyncLogic(AppContext.getInstance(), mCheckVersionHandler, true);
        logic.execute();

    }

    private void checkVersionDialog(final VersionBean bean) {
        new AlertDialog.Builder(this).setTitle("更新").setMessage("是否进行应用更新？")
                .setCancelable(true)
                .setPositiveButton("确定", (dialog, which) -> {
                    mProgressDialog.setIsOut(false);
                    mProgressDialog.setMessage("请稍等，正在下载中...");
                    mProgressDialog.show();
                    new Thread(() -> {
                        DownloadSyncLogic logic = new DownloadSyncLogic(bean, mDownloadHandler);
                        logic.start();
                    }).start();

                }).setNegativeButton("取消", (dialog, which) -> {
            dialog.dismiss();
            KJActivityManager.create().finishActivity(LoadingActivity.this);

        }).setOnKeyListener((dialog, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                return true;
            } else {
                return false;
            }
        }).setCancelable(false).create().show();
    }

    private Handler mCheckVersionHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
            }
            switch (msg.what) {
                case UIHelper.VERSION_SUCCESS:
                    VersionBean bean = (VersionBean) msg.obj;
                    checkVersionDialog(bean);
                    break;
                case UIHelper.VERSION_NO_DATA:
//					Toast.makeText(getApplicationContext(), "当前已经是最新版本", Toast.LENGTH_SHORT).show();
                    login();
                    break;
                case UIHelper.VERSION_FAIL:
//					Toast.makeText(getApplicationContext(), "更新失败", Toast.LENGTH_SHORT).show();
                    login();
                    break;
                default:
                    break;
            }
        }
    };

    private Handler mDownloadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
            }
            if (msg.what == 0) {
                downloadFinish((String) msg.obj);
            }
        }
    };

    private void downloadFinish(String saveFileName) {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        startActivity(i);
    }

    private synchronized void login() {
        LoginReq req = new LoginReq(HttpConfig.POST_URL_DATB_LOGIN,
                LoginSyncLogic.LOGIN_FINGERPRINT);

        LoginSyncLogic logic = new LoginSyncLogic(mAppContext, mContext,
                mLoadingLoginHandler, true, req);
        logic.execute();

    }

    private Runnable mRunnable = new Runnable() {

        @Override
        public void run() {
            startActivity(new Intent(LoadingActivity.this, LoginActivity.class));
            finish();
        }

    };

    private boolean mIsLoading = true;

    private Handler mLoadingLoginHandler = new Handler() {

        @Override
        public void handleMessage(android.os.Message msg) {
            if (!mIsLoading) {
                return;
            }
            Log.i(TAG, "----> mLoadingLoginHandler");
            switch (msg.what) {
                case UIHelper.LOGIN_SUCCESS:
                    if (mIsLoading) {
                        mIsLoading = false;
                        startActivity(new Intent(LoadingActivity.this, LoginActivity.class));
                        finish();
                    }
                    break;
                case UIHelper.LOGIN_FAIL:
                    if (mIsLoading) {
                        mIsLoading = false;
                        startActivity(new Intent(LoadingActivity.this, LoginActivity.class));
                        finish();
                    }
                    break;

                default:
                    break;
            }

        }

        ;
    };

    /* (non-Javadoc)
     * @see android.support.v4.app.Fragment#onDestroy()
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        //FingerprintManager.getInstance().closeSerialPort();
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

}
